package generics;

import java.lang.reflect.Constructor;

/**
 * @author 杨宇
 * @version 1.0 2016/11/1
 */
public class E22_InstantiateGenericType2 {
    public static void main(String[] args) {
        ClassAsFactory<Employee> fe = new ClassAsFactory<Employee>(Employee.class);
        Employee emp = fe.create(1);
        if (emp == null)
            System.out.println("Employee cannot be instantiated!");
        ClassAsFactory<Integer> fi = new ClassAsFactory<Integer>(Integer.class);
        Integer i = fi.create(0);
        if (i == null)
            System.out.println("Integer cannot be instantiated!");
    }
}

class ClassAsFactory<T> {
    Class<T> kind;

    public ClassAsFactory(Class<T> kind) {
        this.kind = kind;
    }

    public T create(int arg) {
        try {
            for (Constructor<?> ctor : kind.getConstructors()) {
                Class<?>[] params = ctor.getParameterTypes();
                if (params.length == 1) {
                    if (params[0] == int.class) {
                        return kind.cast(ctor.newInstance(arg));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

class Employee {
}